/**
 * 
 */
package com.cr.backbone.util;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;
import java.text.DecimalFormat;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;

import com.sun.org.apache.bcel.internal.generic.NEW;

/**
 * @project RaedNote
 * @version 1.0
 * @company
 * @fileType UtilsFile UtilsFile.java
 * @author huxh
 * @date 2012-6-13
 */
/**
 * 
 * @author huxh
 * @date 2012-6-13
 */
public class UtilsFile {
	
	
	/**
	 * 文件保存到服务器
	 * 
	 * @param upload
	 * @param uploadFileName
	 * @return
	 * @throws Exception
	 * @author huxh
	 * @date 2012-6-15
	 */
	public static File saveFileToServer(File upload,String uploadFileName) throws Exception{
		try {
			if(upload ==null || uploadFileName == null || "".equals(uploadFileName))
				return null;
			File srcFile=upload;
			
			
			// 1  保存文件
			// 1.1 保存文件目录
			String key=UtilsConfig.FILE_PATH_UPLOAD_ROOT_FOLDER;
			String realPath  = ServletActionContext.getServletContext().getRealPath(UtilsConfigProperties.getInstance().getProperty(key));//root
			if(realPath == null || "".equals( realPath ) ){
				String ROOT="ROOT";
				realPath  = ServletActionContext.getServletContext().getRealPath(ROOT);//root
				realPath = realPath+"/"+UtilsConfigProperties.getInstance().getProperty(key);
				
				File rootFile =new File(realPath);
				if(!rootFile.exists()){
					rootFile.mkdirs();//创建根目录
				}
			}
			// root
			StringBuffer path=new StringBuffer(realPath);
			
			int beginIndex=uploadFileName.indexOf(".");
			int endIndex=uploadFileName.length();
			String FileSuffix = uploadFileName.substring((beginIndex+1), endIndex);
			// file suffix
			path.append("/");
			path.append(FileSuffix);
			path.append("/");
			// date
			path.append(UtilsDateTime.getCurrentDateString());
			
			//1.2 保存文件名称
			StringBuffer newFileName = new StringBuffer(); 
			//newFileName.append(UtilsDateTime.getCurrentDateTimeString("yyyy-MM-dd_hh:mm:ss"));
			newFileName.append(UtilsDateTime.getCurrentDateTimeString("yyyyMMdd_HHmmss"));
			newFileName.append("_____");
			newFileName.append(FileSuffix);
			newFileName.append("_____");
			newFileName.append(System.currentTimeMillis());
			newFileName.append(".");
			newFileName.append(FileSuffix);
			
			
			// dest file 
//			File destFile=new File(new File(realPath),uploadFileName);
//			if(!destFile.getParentFile().exists()){
//				destFile.getParentFile().mkdirs();
//			}
//			
//			fileUtils.copyFile(srcFile, destFile);

			// new dest file 
			String newPath=UtilsFile.getPath(path.toString());//windos linux 文件夹目录调整
			System.out.println(newPath);
			File newDestFile=new File(new File( newPath ),newFileName.toString());
			if(!newDestFile.getParentFile().exists()){
				newDestFile.getParentFile().mkdirs();
			}
			
			// 文件copy
			UtilsFile.copyFile(srcFile, newDestFile);
			System.out.println(newDestFile.getPath());
			return newDestFile;
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return null;
		
	}



	/**
	 * 根据当前系统，获取文件夹正确目录
	 * 
	 * @param strPath
	 * @return
	 * @author huxh
	 * @date 2012-6-13
	 */
	public static String getPath(String strPath) {
		String[] execString = new String[2];
		String filePath = null;
		
		
		String osName = System.getProperty("os.name");
		if (osName.toLowerCase().startsWith("windows")) {
			// Window System;
			execString[0] = "explorer";
			try {
				filePath = strPath.replace("/", "\\");
			} catch (Exception ex) {
				filePath = strPath;
			}
		} else {
			// Unix or Linux;
			execString[0] = "netscape";
			filePath = strPath;
		}

		
		execString[1] = filePath;
		try {
			//执行目录下文件
			//Runtime.getRuntime().exec(execString);
		} catch (Exception ex) {
			System.out.println("异常啦...");
		}
		
		//路径全部修改为 /
		filePath=strPath.replace("\\", "/");;
		return filePath;
	}

	/**
	 * 文件复制
	 * @param srcFile
	 * @param newDestFile
	 * @author huxh
	 * @throws IOException 
	 * @date 2012-6-14 
	 */
	public static void copyFile(File srcFile, File newDestFile) throws IOException {
		File destFile=newDestFile;
		FileUtils.copyFile(srcFile, destFile);
	}
	
	
	/**
	 * 返回文件的大小的字符串
	 * @return 文件的大小（格式化文本）
	 */
	public static String getFileSizeGMK(long fileSize) {
		DecimalFormat   df   =   new   DecimalFormat("###,##0.00");   
		double s = 1.0 * fileSize;
		if( s > (1024*1024*1024) ){
			return df.format(s/1024/1024/1024)+"G";
		}else if(s > (1024*1024)){
			return df.format(s/1024/1024)+"M";
		}else{
			return getFileSizeKFormat(fileSize);
		}
	}
	
	
	/**
	 * 返回文件的大小的字符串
	 * @return 文件的大小（格式化文本）
	 */
	public static String getFileSizeKFormat(long fileSize) {
		DecimalFormat   df   =   new   DecimalFormat("###,##0.00");   
		if( fileSize >0  ){
			return df.format( getFileSizeKMG(fileSize) )+"K";
		}
		return df.format( 0 )+"K";
	}
	
	/**
	 * 返回文件的大小的字符串
	 * 1024进制
	 * @return 文件的大小（格式化文本）
	 */
	public static Long getFileSizeKMG(long fileSize) {
		if( fileSize > 0){
			double s = 1.0 * fileSize;
			if( s>0 ){
				double ss=s/1024;
				BigDecimal _t = new BigDecimal( ss );
				_t.abs(new MathContext(2,RoundingMode.HALF_UP ));
				ss = _t.longValue();
				return _t.longValue() ;
			}
		}
		return 0l;
	}
	
	
	/**
	 * 获取文件后缀名称
	 * @param fileName
	 * @return
	 * @author huxh
	 * @date 2012-6-14
	 */
	public static String getFileExt(String fileName){

        if(fileName == null)
            return null;
        int pos = fileName.lastIndexOf('.');
        if(pos > 0){
            return fileName.substring(pos+1, fileName.length());
        }else{
            return "";
        }
    }
	
}
